<!--  -->
<template>
    <div class="main_container">
        <div class="custform_nav">
            <div>
                <div class="im-export">
                    <el-button type="success" @click="triggerFileInput">重新导入</el-button>
                    <input type="file" ref="fileInput" v-show="false" @change="importData" accept=".xlsx, .xls, .csv" />
                    <div>
                        <el-button type="primary" @click="exportData">导出信息</el-button>   
                    </div>                 
                </div>
                <el-input v-model="search_data.order_id" size="medium" placeholder="请输入ID搜索" style="width: 200px;"/>
                <el-button type="primary" @click="search">搜索</el-button>
                <el-button type="success" @click="add">添加</el-button>
                <!-- 添加用户弹窗 -->
                <el-dialog v-model="dialogVisible"  width="40%">
                    <div class="add_title">
                        <p>添加工单信息</p>
                    </div>
                    <el-form ref="userForm" :model="add_data" label-width="100px">
                        <el-form-item label="业务ID">
                            <el-input v-model="add_data.business_id" placeholder="请输入业务ID"></el-input>
                        </el-form-item>
                        <el-form :inline="true" :model="formInline" class="demo-form-inline">
                            <el-form-item label="客户ID" label-width="100px">
                                <el-input v-model="add_data.customer_id" placeholder="请输入客户ID"></el-input>
                            </el-form-item>                        
                            <el-form-item label="客户姓名:">
                                <p>{{ add_data.customer_name}}</p>
                            </el-form-item>
                        </el-form>                        
                        <el-form :inline="true" :model="formInline" class="demo-form-inline">
                            <el-form-item label="负责人ID" label-width="100px">
                                <el-input v-model="add_data.staff_id" placeholder="请输入负责人ID"></el-input>                         
                            </el-form-item>
                            <el-form-item label="负责人姓名:">
                                <p>{{ add_data.staff_name}}</p>                         
                            </el-form-item>
                        </el-form>
                        <el-form :inline="true" :model="formInline" class="demo-form-inline">                            
                            <el-form-item label="交易金额" label-width="100px">
                                <el-input v-model="add_data.money" placeholder="请输入交易金额"></el-input>                         
                            </el-form-item>
                            <el-form-item label="工单状态">
                                <el-select v-model="add_data.state" placeholder="工单状态" class = "wo-option">
                                    <el-option
                                        v-for="item in options2"
                                        :key="item.value"
                                        :label="item.label     "
                                        :value="item.value">
                                    </el-option>
                                </el-select>                              
                            </el-form-item>
                        </el-form>                             
                        <el-steps :active="stateMap[add_data.state]" finish-status="success" >
                            <p>>>>>>></p>
                            <el-step title="未生效" :status="getStepStatus(0, add_data.state)"></el-step>
                            <el-step title="进行中" :status="getStepStatus(1, add_data.state)"></el-step>
                            <el-step title="回单" :status="getStepStatus(2, add_data.state)"></el-step>
                            <el-step title="退单" :status="getStepStatus(3, add_data.state)"></el-step>                          
                        </el-steps>
                        <el-form-item label="备注">
                            <el-input
                                type="textarea"
                                :rows="3"
                                placeholder="请输入备注"
                                v-model="add_data.discription">
                            </el-input> 
                        </el-form-item>
                    </el-form>
                    <div class="add_btn">
                        <el-button @click="closeadd">取消</el-button>
                        <el-button type="primary" @click="submitForm">确定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
        <el-table :data="order_tabledata" style="width: 100%">
            <el-table-column label="工单ID" prop="order_id" />
            <el-table-column label="业务ID" prop="business_id" />            
            <el-table-column label="客户" prop="customer_name" />
            <el-table-column label="负责人" prop="staff_name" />
            <el-table-column label="交易金额(￥)" prop="money" />
            <el-table-column label="状态" prop="state">
            <template #default="{ row }">
                <el-tag :color="stateColorMap[row.state]" effect="light">
                    {{ row.state }}
                </el-tag>
            </template>                
            </el-table-column>
            <el-table-column label="创建时间" prop="created_time">
                <template #default="scope">
                    {{ formatDate(scope.row.created_time) }}
                </template>
            </el-table-column>
            <el-table-column label="更新时间" prop="updated_time">
                <template #default="scope">
                    {{ formatDate(scope.row.updated_time) }}
                </template>
            </el-table-column>
            <el-table-column align="right">
                <template #default="scope">
                    <el-button-group>
                        <el-button type="success" size="small" @click="update(scope.row)">
                            修改/详情
                        </el-button>                   
                        <el-button
                            size="small"
                            type="danger"
                            @click="del(scope.row.order_id)"
                        >
                            删除
                        </el-button>
                    </el-button-group>                
                </template>
            </el-table-column>       
        </el-table>           
        <el-dialog v-model="dialogVisible_update"  width="40%">
            <div class="add_title">
                <p>修改工单信息</p>
            </div>
            <el-form ref="userForm" :model="update_data" label-width="100px">
                <el-form-item label="业务ID">
                    <el-input v-model="update_data.business_id" placeholder="请输入业务ID"></el-input>
                </el-form-item>
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="客户ID" label-width="100px">
                        <el-input v-model="update_data.customer_id" placeholder="请输入客户ID"></el-input>
                    </el-form-item>                        
                    <el-form-item label="客户姓名:">
                        <p>{{ update_data.customer_name }}</p>
                    </el-form-item>
                </el-form>                        
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="负责人ID" label-width="100px">
                        <el-input v-model="update_data.staff_id" placeholder="请输入负责人ID"></el-input>                         
                    </el-form-item>
                    <el-form-item label="负责人姓名:">
                        <p>{{ update_data.staff_name}}</p>                         
                    </el-form-item>
                </el-form>
                <el-form :inline="true" :model="formInline" class="demo-form-inline">                            
                    <el-form-item label="交易金额" label-width="100px">
                        <el-input v-model="update_data.money" placeholder="请输入交易金额"></el-input>                         
                    </el-form-item>
                    <el-form-item label="工单状态">
                        <el-select v-model="update_data.state" placeholder="工单状态" class = "wo-option">
                            <el-option
                                v-for="item in options2"
                                :key="item.value"
                                :label="item.label     "
                                :value="item.value">
                            </el-option>
                        </el-select>                              
                    </el-form-item>
                </el-form>                             
                <el-steps :active="stateMap[update_data.state]" finish-status="success" >
                    <p>>>>>>></p>
                    <el-step title="未生效" :status="getStepStatus(0, update_data.state)"></el-step>
                    <el-step title="进行中" :status="getStepStatus(1, update_data.state)"></el-step>
                    <el-step title="回单" :status="getStepStatus(2, update_data.state)"></el-step>
                    <el-step title="退单" :status="getStepStatus(3, update_data.state)"></el-step>                          
                </el-steps>
                <el-form-item label="备注">
                    <el-input
                        type="textarea"
                        :rows="3"
                        placeholder="请输入备注"
                        v-model="update_data.discription">
                    </el-input> 
                </el-form-item>       
            </el-form>
            <div class="add_btn">
                <el-button @click="closeupdate">取消</el-button>
                <el-button type="primary" @click="submitForm_update">确定</el-button>
            </div>
        </el-dialog>        
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
import * as XLSX from 'xlsx';

const now = new Date().toISOString(); // 实时时间戳

const api = {
    searchurl: "/api/wo/search", 
    loadurl: "/api/wo",
    addurl: "/api/wo/add",
    updateurl: "/api/wo/update",   
    deleteurl: "/api/wo/delete",
    importurl: "/api/wo/import",
    update_performance: "api/wo/update_performance"        
};

const search_data = ref({
    order_id: ''
});

// 时间格式切换
function formatDate(isoString) {
    const date = new Date(isoString);
    const utcDate = new Date(date.toISOString()); // 确保输入是 UTC 时间
    utcDate.setUTCHours(utcDate.getUTCHours() - 8); // 转换为东八区时间

    const year = utcDate.getFullYear();
    const month = String(utcDate.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
    const day = String(utcDate.getDate()).padStart(2, '0');
    const hours = String(utcDate.getHours()).padStart(2, '0');
    const minutes = String(utcDate.getMinutes()).padStart(2, '0');
    const seconds = String(utcDate.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const order_tabledata = ref([]);

// *客户信息导出功能
const exportData = () => {
    // 创建一个工作簿
    const wb = XLSX.utils.book_new();

    // 将数据转换为工作表
    const ws = XLSX.utils.json_to_sheet(order_tabledata.value);
    console.log(order_tabledata.value);

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'order');

    // 导出文件
    XLSX.writeFile(wb, 'order.xlsx');
    ElMessage.success('导出成功');
};

//*客户信息导入
const importData = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    try {
        // 使用 FileReader 读取文件内容
        const reader = new FileReader();
        reader.onload = (e) => {
            const data = e.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0]; // 获取第一个
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet); // 将工作表转换为 JSON 格式

            // 转换为后端期望的格式
            const order = jsonData.map((row) => ({
                order_id: row['order_id'], 
                customer_id: row['customer_id'], 
                staff_id: row['staff_id'],
                business_id: row['business_id'],
                money: row['money'],
                discription: row['discription'],
                state: row['state'],
                customer_name: row['customer_name'],
                staff_name: row['staff_name'],               
                created_time: new Date().toISOString(), 
                updated_time: new Date().toISOString() 
            }));

            // 发送 JSON 数据到后端
            axios.post(api.importurl, order, {
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                ElMessage.success('导入成功');
                console.log(response.data);
                loaddate(); // 刷新数据
            })
            .catch(error => {
                ElMessage.error('导入失败：' + error.message);
                console.error(error);
            });
        };
        reader.readAsBinaryString(file); // 读取文件内容
    } catch (error) {
        ElMessage.error('导入失败：' + error.message);
        console.error(error);
    }
};

const triggerFileInput = () => {
    const fileInput = document.querySelector('input[type="file"]');
    if (fileInput) {
        fileInput.click();
    }
};

// *搜索
const search = async () => {
    if (!search_data.value.order_id){ 
        loaddate(); 
        return;
    }
    try {
        let result = await axios.post(api.searchurl, {
            order_id: search_data.value.order_id
        });
        if(result.data){
            order_tabledata.value = [result.data];
            ElMessage.success('查询成功');
        }else{
            ElMessage.error('未匹配到相关查询');
        }
    } catch (error) {
        ElMessage.error('搜索失败:输入了非法字符或者长度不符');
        console.error(error);
    }
};

//*添加

const dialogVisible = ref(false); // 控制弹窗的显示与隐藏

const add_data = ref({
    order_id: null,
    customer_id: null, 
    staff_id: null,
    business_id: null,
    state: '',    
    discription: '',
    money: null,
    created_time: now,
    updated_time: now,
    customer_name: '',
    staff_name: ''
});

const add = () => {
  dialogVisible.value = true;
};
const value = ref();

const options = ref([
    { value: "未生效", label: "未生效" },
    { value: "进行中", label: "进行中" },
    { value: "回单", label: "回单" },
    { value: "退单", label: "退单" }
]);

const options2 = ref([
    { value: "未生效", label: "未生效" },
    { value: "进行中", label: "进行中" },
    { value: "回单", label: "回单" },
    { value: "退单", label: "退单" }
]);

const closeadd = () => {
    add_data.value = {
        order_id: null,
        customer_id: null, 
        staff_id: null,
        business_id: null,
        state: '',    
        discription: '',
        money: null,
        created_time: now,
        updated_time: now,
        customer_name: '',
        staff_name: ''    
    };
    dialogVisible.value = false;
};

// 提交表单
const submitForm = async () => {
    try {
        const response = await axios.post(api.addurl, add_data.value);      
        ElMessage.success('用户添加成功');
        closeadd();
        loaddate(); // 刷新数据
    } catch (error) {
        ElMessage.error('添加失败：' + error.message);
        console.error(error);
    }
};

// *修改
const dialogVisible_update = ref(false); // 控制弹窗的显示与隐藏

const update_data = ref({
    order_id: null,
    customer_id: null, 
    staff_id: null,
    business_id: null,
    state: '',    
    discription: '',
    money: null,
    created_time: null,
    updated_time: now,
    customer_name: '',
    staff_name: ''    
});

const closeupdate = () => {
    update_data.value = {
        order_id: null,
        customer_id: null, 
        staff_id: null,
        business_id: null,
        state: '',    
        discription: '',
        money: null,
        created_time: null,
        updated_time: now,
        customer_name: '',
        staff_name: ''        
    };
    dialogVisible_update.value = false;
};

const update = (row) => {
    update_data.value.order_id = row.order_id;
    update_data.value.customer_id = row.customer_id;
    update_data.value.staff_id = row.staff_id;
    update_data.value.business_id = row.business_id;
    update_data.value.state = row.state;
    update_data.value.discription = row.discription;
    update_data.value.money = row.money;
    update_data.value.created_time = row.created_time;
    update_data.value.updated_time = row.updated_time;
    update_data.value.customer_name = row.customer_name;
    update_data.value.staff_name = row.staff_name;
    nextTick(() => {
        dialogVisible_update.value = true;
    });
};

const submitForm_update = async () => {
    try {        
        const response = await axios.put(`${api.updateurl}/${update_data.value.order_id}`, update_data.value);
        ElMessage.success('用户更新成功');
        console.log(response.data);
        closeupdate();
        loaddate(); // 刷新数据
    } catch (error) {
        ElMessage.error('更新失败：' + error.message);
        console.error(error);
    }
};

// *删除
const del = async (orderId) => {
    try {
        const confirmDelete = confirm("确定要删除该用户吗？");
        if (!confirmDelete) {
            return;
        }
        let result = await axios.delete(api.deleteurl + `/${orderId}`);
        ElMessage.success('删除成功');
        loaddate();
    } catch (error) {
        ElMessage.error('删除失败：' + error.message);
        console.error(error);
    }
};

// 刷新页面

// *加载
const loaddate = async () => {
    try {
        let result = await axios.get(api.loadurl);
        await axios.get(api.update_performance);
        order_tabledata.value = result.data; 
        console.log(order_tabledata.value.state);
    } catch (error) {
        ElMessage.error('加载数据失败：' + error.message);
        console.error(error);
    }
};
  
loaddate();

const stateMap = {
    '未生效': 0, 
    '进行中': 1, 
    '回单': 2,
    '退单': 3 
};

const stateColorMap = {
    "未生效": "lightgray",
    "进行中": "lightblue",
    "回单": "lightgreen",
    "退单": "Tomato"
}

// 获取步骤状态
function getStepStatus(stepIndex, currentState) {
    const activeStep = stateMap[currentState];
    if(stateMap[currentState] == 3 && stepIndex === activeStep){
        return 'error';
    }
    if (stepIndex === activeStep) {
        return 'success'; // 当前步骤
    } else if (stepIndex < activeStep) {
        return 'wait'; // 已完成的步骤
    } else {
        return 'wait'; // 未完成的步骤
    }
}
</script>

<style scoped>

    .add_title{
        padding-bottom:20px;
    }
    .add_title>p{
        text-align: center;
        font-size: 20px;
    }

    .add_btn{
        padding: 10px;
        text-align: center;
    }

    .common-layout>ul {
        height: 80px;
    }
    .el-menu el-menu--horizontal el-menu-demo{
        min-width: 1588px;
    }
    .main_container{
        min-width: 80% ;

    }
    .custform_nav{
        margin: 20px;
    }
    .custform_nav>div{
        min-width: 380px;
        display: flex;

    }
    .im-export{
        display: flex;
        width: 200px;
        padding-right: 72%;
    }
    .im-export>button{
        margin-right:20px;
    }
    .wo-option{
        width: 100px;
    }
</style>


